#!/usr/bin/env python
import time
import XenAPI
import parse_rrd
import os,sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from com.instance_option import get_instance_ip_info


class check_host_vm_status():
    def __init__(self,host_ip,passowrd):
        self.host_ip=host_ip
        self.url = "https://"+host_ip+":443"
        self.password=passowrd
        
    def get_xapi_session(self):
        try:
            session = XenAPI.Session(self.url)
            session.xenapi.login_with_password('root',self.password)
        except XenAPI.Failure, e:
            if e.details[0]=='HOST_IS_SLAVE':
                    ses = XenAPI.Session('https://'+e.details[1]+":443")
                    ses.xenapi.login_with_password('root',self.password)
                    return ses
        return session
    
    def get_all_instance_info(self):
        return get_instance_ip_info()
        
    def print_latest_host_data(self,rrd_updates):
        param_list=[]
        data_list=[]
        host_param_data={}
        for param in rrd_updates.get_host_param_list():
            if param != "":
                max_time=0
                data=""
                for row in range(rrd_updates.get_nrows()):
                    epoch = rrd_updates.get_row_time(row)
                    dv = str(rrd_updates.get_host_data(param,row))
                    if epoch > max_time:
                        param_list.append(param)
                        max_time = epoch
                        data = dv
                        data_list.append(data)
                        host_param_data=dict(zip(param_list,data_list))
        return host_param_data 
              
    
    
    def get_latest_vm_data(self,rrd_updates,uuid):
        param_list=[]
        data_list=[]
        vm_param_data={}
        if  uuid in rrd_updates.get_vm_list():
            for param in rrd_updates.get_vm_param_list(uuid):
                if param != "":
                    max_time=0
                    data=""
                    for row in range(rrd_updates.get_nrows()):
                        epoch = rrd_updates.get_row_time(row)
                        dv = str(rrd_updates.get_vm_data(uuid,param,row))
                        if epoch > max_time:
                            param_list.append(param)
                            max_time = epoch
                            data = dv
                            data_list.append(data)
                            vm_param_data=dict(zip(param_list,data_list))
            return vm_param_data
        else:
            return None
    
    def build_vm_graph_data(self,rrd_updates,vm_uuid,param):
        time_now = int(time.time())
        for param_name in rrd_updates.get_vm_param_list(vm_uuid):
            if param_name == param:
                data = "#%s  Seconds Ago" % param
                for row in range(rrd_updates.get_nrows()):                
                    epoch = rrd_updates.get_row_time(row)
                    data = str(rrd_updates.get_vm_data(vm_uuid, param_name, row))
                    data += "\n%-14s %s" % (data, time_now - epoch)
                return data
    
    def get_vm_param_values(self,uuid):
        session=self.get_xapi_session()
        rrd_updates = parse_rrd.RRDUpdates()                                                                                                                              
        params = {}
        params['cf'] = "AVERAGE"
        params['start'] = int(time.time()) - 10
        params['interval'] = 5
        params['host'] = ""
        rrd_updates.refresh(session.handle, params,self.url)
        vm_param_value=self.get_latest_vm_data(rrd_updates,uuid)
        return vm_param_value
    
    def get_host_param_values(self):
        session=self.get_xapi_session()
        rrd_updates = parse_rrd.RRDUpdates()
        params = {}
        params['cf'] = "AVERAGE"
        params['start'] = int(time.time()) - 10
        params['interval'] = 5
        params['host'] = ""
        rrd_updates.refresh(session.handle, params, self.url)
        host_param_data=self.print_latest_host_data(rrd_updates)
        return host_param_data
    
    def get_host_list(self):
        session=self.get_xapi_session()
        hosts=session.xenapi.host.get_all()
        for x in hosts:
            ses=session.xenapi.host.get_record(x)
            if ses['address'] == self.host_ip:
                nametabl=ses['hostname']
        data_list=[]
        host_param=['name','value','ipaddress']
        host_param_data=self.get_host_param_values()
        data_list.append(nametabl)
        data_list.append(host_param_data)
        data_list.append(self.host_ip)
        host_value=dict(zip(host_param,data_list))
        return host_value
        
    def get_vm_list(self):
        session=self.get_xapi_session()
        vms = session.xenapi.VM.get_all()
        vm_list=[]
        vms_info=self.get_all_instance_info()
        vm_param=['name','uuid','value','ipaddress']
        for vm in vms:
            record = session.xenapi.VM.get_record(vm)
            if not(record["is_a_template"]) and not(record["is_control_domain"] and record["power_state"] == "Running"):
                name = record["name_label"]
                uuid= record["uuid"]
                vm_params_value=self.get_vm_param_values(uuid)
                if vm_params_value == None:
                    continue
                data_list=[]
                data_list.append(name)
                data_list.append(uuid)
                data_list.append(vm_params_value)
                for vminfo in vms_info:
                    if name == vminfo['instance_name']:
                        data_list.append(vminfo['private_ip_address'])
                vm_value=dict(zip(vm_param,data_list))
                vm_list.append(vm_value)
        return vm_list
'''
def main():
    #get_all_instance_info()
    check_status=check_host_vm_status('192.168.194.32','devicevmhz!')
    host_v=check_status.get_host_list()
    print host_v

main()
'''
